package cn.com.libertymutual.sp.action.upload;

import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.io.FileUtils;
import org.apache.commons.lang.StringUtils;
import org.apache.poi.hssf.usermodel.HSSFCell;
import org.apache.poi.hssf.usermodel.HSSFRow;
import org.apache.poi.hssf.usermodel.HSSFSheet;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.xssf.usermodel.XSSFCell;
import org.apache.poi.xssf.usermodel.XSSFRow;
import org.apache.poi.xssf.usermodel.XSSFSheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.cloud.context.config.annotation.RefreshScope;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;

import cn.com.libertymutual.sp.req.FileUploadParam;
import cn.com.libertymutual.sp.service.api.ScoreService;
import cn.com.libertymutual.sp.sftp.SFTP2;
import cn.com.libertymutual.sys.nio.NioClient;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import sun.misc.BASE64Decoder;

@RefreshScope // 刷新配置无需重启服务
@SuppressWarnings("restriction")
@RestController
@RequestMapping(value = "/admin/uploadWeb")
public class FileUploadControllerWeb {

	/** 上传文件同一目录 */
	@Value("${file.transfer.uploadImagesPath}")
	private String uploadImagesPath;

	private Logger log = LoggerFactory.getLogger(getClass());
	// @Autowired
	// private SFTP sftp;
	///@Autowired
	///private SFTP2 sftp2;
	@Autowired
	private NioClient nioClient;
	/**
	 * 文件上传(单文件上传)
	 *
	 */
	// @RequestMapping(value = "/single")
	// @ResponseBody
	// public String upload(@RequestParam("file") MultipartFile file) {
	// if (file.isEmpty()) {
	// return "文件为空";
	// }
	// // 获取文件名
	// String fileName = file.getOriginalFilename();
	// log.info("上传的文件名为：" + fileName);
	// // 获取文件的后缀名
	// String suffixName = fileName.substring(fileName.lastIndexOf("."));
	// log.info("上传的后缀名为：" + suffixName);
	// // String filePath = "E://";
	// String filePath = this.uploadImagesPath;
	// // 解决中文问题，liunx下中文路径，图片显示问题
	// SimpleDateFormat df = new SimpleDateFormat("yyyyMMddHHmmss");// 设置日期格式
	// fileName = df.format(new Date()) + suffixName;
	// // File dest = new File(filePath + fileName);
	// File dirPath = new File(filePath);
	// if (!dirPath.exists()) {
	// dirPath.mkdirs();
	// }
	// File tempFile = new File(filePath, fileName);
	// String path = tempFile.getPath();
	// // sftp.SFTPupload(path);
	// log.info("tempFile path ===>{}", path);
	// // sftp2.SFTPupload(path);
	// try {
	// file.transferTo(tempFile);
	// log.info("首次上传文件的大小-->:{}", new File(path).length());
	// return path.substring(path.indexOf("/sticcxb/"), path.length());
	// } catch (IllegalStateException e) {
	// e.printStackTrace();
	// } catch (IOException e) {
	// e.printStackTrace();
	// }
	// return "上传失败";
	// }
	//
	// /**
	// * 文件上传(单文件上传 流形式)
	// *
	// */
	// @RequestMapping(value = "/stream")
	// @ResponseBody
	// public String uploadStream(@RequestParam("file") MultipartFile file) {
	// if (file.isEmpty()) {
	// return "文件为空";
	// }
	// // 获取文件名
	// String fileName = file.getOriginalFilename();
	// log.info("上传的文件名为：" + fileName);
	// // 获取文件的后缀名
	// String suffixName = fileName.substring(fileName.lastIndexOf("."));
	// log.info("上传的后缀名为：" + suffixName);
	// // String filePath = "E://";
	// String filePath = this.uploadImagesPath;
	// BufferedOutputStream stream = null;
	// // 解决中文问题，liunx下中文路径，图片显示问题
	// SimpleDateFormat df = new SimpleDateFormat("yyyyMMddHHmmss");// 设置日期格式
	// fileName = df.format(new Date()) + suffixName;
	//
	// File dirPath = new File(filePath);
	// if (!dirPath.exists()) {
	// dirPath.mkdirs();
	// }
	//
	// try {
	// File tempFile = new File(filePath, fileName);
	//
	// log.info("上传前文件的大小-->:{}", tempFile.length());
	// String path = tempFile.getPath();
	// log.info("tempFile path ===>{}", path);
	//
	// byte[] bytes = file.getBytes();
	// stream = new BufferedOutputStream(new FileOutputStream(tempFile));
	// stream.write(bytes);
	// stream.close();
	// log.info("流上传后文件的大小-->:{}", tempFile.length());
	// return path.substring(path.indexOf("/sticcxb/"), path.length());
	// } catch (IOException e1) {
	// e1.printStackTrace();
	// }
	// return "upload failed";
	// }
	//
	// /**
	// * 多文件上传 主要是使用了MultipartHttpServletRequest和MultipartFile
	// */
	// @RequestMapping(value = "/many", method = RequestMethod.POST)
	// public @ResponseBody List<String> batchUpload(HttpServletRequest request) {
	// List<MultipartFile> files = ((MultipartHttpServletRequest)
	// request).getFiles("file");
	//
	// MultipartFile file = null;
	// List<String> list = new ArrayList<String>();
	// for (int i = 0; i < files.size(); ++i) {
	// file = files.get(i);
	// if (!file.isEmpty()) {
	// try {
	// String fileName = file.getOriginalFilename();
	// log.info("上传的文件名为：" + fileName);
	// // 获取文件的后缀名
	// String suffixName = fileName.substring(fileName.lastIndexOf("."));
	// log.info("上传的后缀名为：" + suffixName);
	// // 文件上传后的路径
	// // String filePath = "E://";
	// String filePath = this.uploadImagesPath;
	// // 解决中文问题，liunx下中文路径，图片显示问题
	// SimpleDateFormat df = new SimpleDateFormat("yyyyMMddHHmmss");// 设置日期格式
	// fileName = df.format(new Date()) + suffixName;
	//
	// File dirPath = new File(filePath);
	// if (!dirPath.exists()) {
	// dirPath.mkdirs();
	// }
	// // File dest = new File(filePath , fileName);
	// // 检测是否存在目录
	// // if (!dest.getParentFile().exists()) {
	// // dest.getParentFile().mkdirs();
	// // }
	// File tempFile = new File(filePath, fileName);
	// file.transferTo(tempFile);
	//
	// // String src = filePath + fileName;
	// String path = tempFile.getPath();
	// log.info("首次上传文件的大小-->:{}", tempFile.length());
	// // sftp.SFTPupload(path);
	// log.info("tempFile path ===>{}", path);
	// sftp2.SFTPupload(path);
	// list.add(path.substring(path.indexOf("/sticcxb/"), path.length()));
	// } catch (IllegalStateException e) {
	// e.printStackTrace();
	// } catch (IOException e) {
	// e.printStackTrace();
	// } catch (Exception e) {
	//
	// log.info("You failed to upload " + i + " => " + e.getMessage());
	// }
	// } else {
	// log.info("You failed to upload " + i + " because the file was empty.");
	// }
	// }
	// return list;
	// }
	//
	// @ApiImplicitParams(value = { @ApiImplicitParam(name = "filepath", value =
	// "带后缀的文件全名") })
	// @RequestMapping(value = "/getByName", method = RequestMethod.GET)
	// public void output(String filepath, HttpServletRequest request,
	// HttpServletResponse response) throws IOException {
	// OutputStream os = response.getOutputStream();
	// try {
	// response.reset();
	// response.setContentType("image/jpeg; charset=utf-8");
	// File file = new File(filepath);
	// if (file != null && file.exists()) {
	// log.info("write file");
	// os.write(FileUtils.readFileToByteArray(file));
	// os.flush();
	// }
	// } finally {
	// if (os != null) {
	// os.close();
	// }
	// }
	// }
	//
	// @RequestMapping(value = "/upload", method = RequestMethod.POST)
	// public String uploadImg(String file) {
	//
	// log.info("imgbase--:" + file);
	// String path = GenerateImage(file);
	// return path;
	//
	// }
	//
	// public String GenerateImage(String imgStr) {
	// if (imgStr == null) // 图像数据为空
	// return null;
	// BASE64Decoder decoder = new BASE64Decoder();
	// try {
	// // Base64解码
	// byte[] b = decoder.decodeBuffer(imgStr);
	// for (int i = 0; i < b.length; ++i) {
	// if (b[i] < 0) {// 调整异常数据
	// b[i] += 256;
	// }
	// }
	// // 生成jpeg图片
	// SimpleDateFormat df = new SimpleDateFormat("yyyyMMddHHmmss");//设置日期格式
	// String time = df.format(new Date());
	// String imgFilePath = uploadImagesPath+time+".jpg";
	//// String imgFilePath =
	// "/app/saleplatform/web/admin-cxb/image/"+df.format(new Date())+".jpg";
	// OutputStream out = new FileOutputStream(imgFilePath);
	// out.write(b);
	// out.flush();
	// out.close();
	// //sftp
	// File tempFile = new File(uploadImagesPath , time+".jpg");
	// String path = tempFile.getPath();
	// sftp2.SFTPupload(path);
	// return path.substring(path.indexOf("/sticcxb/"), path.length());
	// } catch (Exception e) {
	// return null;
	// }
	// }

	@RequestMapping(value = "/single")
	@ResponseBody
	public String upload(@RequestParam("file") MultipartFile file, String parampath) {
		if (file.isEmpty()) {
			return "文件为空";
		}
		// 获取文件名
		String fileName = file.getOriginalFilename();
		log.info("上传的文件名为：{}", fileName);
		// 获取文件的后缀名
		String suffixName = fileName.substring(fileName.lastIndexOf("."));
		log.info("上传的后缀名为：" + suffixName);
		String filePath = "E://image/"+parampath;
//		String filePath = this.uploadImagesPath + parampath;
		// 解决中文问题，liunx下中文路径，图片显示问题
		SimpleDateFormat df = new SimpleDateFormat("yyyyMMddHHmmssSSS");// 设置日期格式
		fileName = df.format(new Date()) + suffixName;
		// File dest = new File(filePath + fileName);
		File dirPath = new File(filePath);
		if (!dirPath.exists()) {
			dirPath.mkdirs();
		}
		File tempFile = new File(filePath, fileName);
		String path = tempFile.getPath();
		// sftp.SFTPupload(path);
		log.info("tempFile path ===>{}", path);
		// sftp2.SFTPupload(path);
		try {
			file.transferTo(tempFile);
			tempFile.setReadable(true, false);	//add by bob.kuang 20180502
			
			log.info("首次上传文件的大小-->:{}", new File(path).length());
			log.info("tempFile path ===>{}", path);
//			sftp2.SFTPupload(path, parampath);
			nioClient.upload(path, parampath);
			 return path;
//			return path.substring(path.indexOf("/sticcxb/"), path.length());
		} catch (IllegalStateException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}
		return "上传失败";
	}

	/**
	 * 文件上传(单文件上传 流形式)
	 *
	 */
	@RequestMapping(value = "/stream")
	@ResponseBody
	public String uploadStream(@RequestParam("file") MultipartFile file, FileUploadParam parampath) {
		if (file.isEmpty()) {
			return "文件为空";
		}
		// 获取文件名
		String fileName = file.getOriginalFilename();
		log.info("上传的文件名为：" + fileName);
		// 获取文件的后缀名
		String suffixName = fileName.substring(fileName.lastIndexOf("."));
		log.info("上传的后缀名为：" + suffixName);
		// String filePath = "E://";
		String filePath = this.uploadImagesPath + parampath.getParampath() + "/";
		BufferedOutputStream stream = null;
		// 解决中文问题，liunx下中文路径，图片显示问题
		SimpleDateFormat df = new SimpleDateFormat("yyyyMMddHHmmssSSS");// 设置日期格式
		fileName = df.format(new Date()) + suffixName;

		File dirPath = new File(filePath);
		if (!dirPath.exists()) {
			dirPath.mkdirs();
		}

		try {
			File tempFile = new File(filePath, fileName);

			log.info("上传前文件的大小-->:{}", tempFile.length());
			String path = tempFile.getPath();
			log.info("tempFile path ===>{}", path);

			byte[] bytes = file.getBytes();
			stream = new BufferedOutputStream(new FileOutputStream(tempFile));
			stream.write(bytes);
			stream.close();
			log.info("流上传后文件的大小-->:{}", tempFile.length());
			log.info("tempFile path ===>{}", path);
//			sftp2.SFTPupload(path, parampath.getParampath());
			nioClient.upload(path, parampath.getParampath());
			return path.substring(path.indexOf("/sticcxb/"), path.length());
		} catch (IOException e1) {
			e1.printStackTrace();
		}
		return "upload failed";
	}

	/**
	 * 多文件上传 主要是使用了MultipartHttpServletRequest和MultipartFile
	 */
	@RequestMapping(value = "/many", method = RequestMethod.POST)
	public @ResponseBody List<String> batchUpload(HttpServletRequest request, FileUploadParam parampath) {
//		public @ResponseBody List<String> batchUpload(HttpServletRequest request, String parampath) {
		List<MultipartFile> files = ((MultipartHttpServletRequest) request).getFiles("file");
		log.info("====parampath===:{}", parampath.toString());
		log.info("====files size===:{}", files.size());
		MultipartFile file = null;
		List<String> list = new ArrayList<String>();
		for (int i = 0; i < files.size(); ++i) {
			file = files.get(i);
			if (!file.isEmpty()) {
				try {
					String fileName = file.getOriginalFilename();
					log.info("上传的文件名为：{}", fileName);
					// 获取文件的后缀名
					String suffixName = fileName.substring(fileName.lastIndexOf("."));
					log.info("上传的后缀名为：{}", suffixName);
//					String filePath = "E://image/"+parampath;
					// 文件上传后的路径
					String filePath = this.uploadImagesPath + parampath.getParampath() + "/";
					// 解决中文问题，liunx下中文路径，图片显示问题
					SimpleDateFormat df = new SimpleDateFormat("yyyyMMddHHmmssSSS");// 设置日期格式
					fileName = df.format(new Date()) + suffixName;

					File dirPath = new File(filePath);
					if (!dirPath.exists()) {
						dirPath.mkdirs();
					}
					File tempFile = new File(filePath, fileName);
					/*if( !tempFile.exists() ) {
						tempFile.createNewFile();
					}
					tempFile.setReadable(true, false);*/
					
					file.transferTo(tempFile);
					tempFile.setReadable(true, false);	//add by bob.kuang 20180502

					String path = tempFile.getPath();
					log.info("首次上传文件的大小-->:{}", tempFile.length());
					log.info("tempFile path ===>{}", path);
//					sftp2.SFTPupload(path, parampath.getParampath());
					nioClient.upload(path, parampath.getParampath());
					list.add(path.substring(path.indexOf("/sticcxb/"), path.length()));
//					nioClient.upload(path, parampath);
//					list.add(path);
				} catch (IllegalStateException e) {
					e.printStackTrace();
				} catch (IOException e) {
					e.printStackTrace();
				} catch (Exception e) {

					log.info("You failed to upload {} => {}", i, e.getMessage());
				}
			} else {
				log.info("You failed to upload {} because the file was empty.", i);
			}
		}
		return list;
	}

	@ApiImplicitParams(value = { @ApiImplicitParam(name = "filepath", value = "带后缀的文件全名") })
	@RequestMapping(value = "/getByName", method = RequestMethod.GET)
	public void output(String filepath, HttpServletRequest request, HttpServletResponse response) throws IOException {
		OutputStream os = response.getOutputStream();
		try {
			response.reset();
			response.setContentType("image/jpeg; charset=utf-8");
			File file = new File(filepath);
			if (file != null && file.exists()) {
				log.info("write file");
				os.write(FileUtils.readFileToByteArray(file));
				os.flush();
			}
		} finally {
			if (os != null) {
				os.close();
			}
		}
	}

	@RequestMapping(value = "/upload", method = RequestMethod.POST)
	public String uploadImg(String file, String parampath) {

		log.info("imgbase--parampath--{}:", parampath);
		String path = GenerateImage(file, parampath);
		return path;

	}

	public String GenerateImage(String imgStr, String parampath) {
		if (imgStr == null) // 图像数据为空
			return null;
		BASE64Decoder decoder = new BASE64Decoder();
		try {
			// Base64解码
			byte[] b = decoder.decodeBuffer(imgStr);
			for (int i = 0; i < b.length; ++i) {
				if (b[i] < 0) {// 调整异常数据
					b[i] += 256;
				}
			}
			// 生成jpeg图片
			SimpleDateFormat df = new SimpleDateFormat("yyyyMMddHHmmss");// 设置日期格式
			String time = df.format(new Date());

			File dirPath = new File(uploadImagesPath + parampath + "/");
			if (!dirPath.exists()) {
				dirPath.mkdirs();
			}

			String imgFilePath = uploadImagesPath + parampath + "/" + time + ".jpg";
			OutputStream out = new FileOutputStream(imgFilePath);
			out.write(b);
			out.flush();
			out.close();
			// sftp
			File tempFile = new File(imgFilePath);
			String path = tempFile.getPath();
//			sftp2.SFTPupload(path, parampath);
			nioClient.upload(path, parampath);
			return path.substring(path.indexOf("/sticcxb/"), path.length());
		} catch (Exception e) {
			return null;
		}
	}

	@RequestMapping(value = "/testUpload", method = RequestMethod.POST)
	public @ResponseBody List<String> testUpload(HttpServletRequest request, FileUploadParam parampath) {
//		public @ResponseBody List<String> batchUpload(HttpServletRequest request, String parampath) {
		List<MultipartFile> files = ((MultipartHttpServletRequest) request).getFiles("file");
		log.info("====parampath===:{}", parampath.toString());
		log.info("====files size===:{}", files.size());
		MultipartFile file = null;
		List<String> list = new ArrayList<String>();
		for (int i = 0; i < files.size(); ++i) {
			file = files.get(i);
			if (!file.isEmpty()) {
				try {
					String fileName = file.getOriginalFilename();
					log.info("上传的文件名为：{}", fileName);
					// 获取文件的后缀名
					String suffixName = fileName.substring(fileName.lastIndexOf("."));
					log.info("上传的后缀名为：{}", suffixName);
//					String filePath = "E://image/"+parampath;
					// 文件上传后的路径
					String filePath = this.uploadImagesPath + parampath.getParampath() + "/";
					// 解决中文问题，liunx下中文路径，图片显示问题
					SimpleDateFormat df = new SimpleDateFormat("yyyyMMddHHmmssSSS");// 设置日期格式
					fileName = df.format(new Date()) + suffixName;

					File dirPath = new File(filePath);
					if (!dirPath.exists()) {
						dirPath.mkdirs();
					}
					File tempFile = new File(filePath, fileName);
					/*if( !tempFile.exists() ) {
						tempFile.createNewFile();
					}
					tempFile.setReadable(true, false);
					*/
					file.transferTo(tempFile);

					String path = tempFile.getPath();
					log.info("首次上传文件的大小-->:{}", tempFile.length());
					log.info("tempFile path ===>{}", path);
//					sftp2.SFTPupload(path, parampath.getParampath());
					nioClient.upload(path, parampath.getParampath());
					list.add(path.substring(path.indexOf("/sticcxb/"), path.length()));
//					nioClient.upload(path, parampath);
//					list.add(path);
				} catch (IllegalStateException e) {
					e.printStackTrace();
				} catch (IOException e) {
					e.printStackTrace();
				} catch (Exception e) {

					log.info("You failed to upload " + i + " => " + e.getMessage());
				}
			} else {
				log.info("You failed to upload " + i + " because the file was empty.");
			}
		}
		return list;
	}


}
